package com.filter;

import com.alibaba.fastjson2.JSONObject;
import com.comment.CommentResult;
import com.constant.PosConstant;
import com.domain.entity.User;
import com.utils.JWTUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 管理员过滤器
 */
public class AdminFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 2. 获取指定的header
        String header = request.getHeader(JWTUtils.HEADER);
        if (StringUtils.isBlank(header)) {
            // 解析出错
            servletResponse.setContentType("application/json;charset=utf-8");
            CommentResult<Void> error = CommentResult.error(403, "没有登录，请先登录");
            // 提前返回无权限信息
            servletResponse.getWriter().print(JSONObject.toJSONString(error));
            return;
        }

        // 3. 去除token的前缀
        String token = header.replace(JWTUtils.TOKEN_PREFIX, "");


        // 4. 解析token转换为token
        User user = JWTUtils.parseToken(token);
        if (user == null) {
            // 解析出错
            servletResponse.setContentType("application/json;charset=utf-8");
            CommentResult<Void> error = CommentResult.error(403, "没有登录，请先登录");
            // 提前返回无权限信息
            servletResponse.getWriter().print(JSONObject.toJSONString(error));
            return;
        }

        // 5. 判断是否为管理员
        if (!PosConstant.ADMIN.equals(user.getPos())) {
            // 非管理员用户
            // 解析出错
            servletResponse.setContentType("application/json;charset=utf-8");
            CommentResult<Void> error = CommentResult.error(405, "非管理员用户，请联系管理员");
            // 提前返回无权限信息
            servletResponse.getWriter().print(JSONObject.toJSONString(error));
            return;
        }

        // 6. 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
